/*
 * AbsPushProgress.java
 * business
 *
 * Created by ChenTao on 2016/10/13.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.data.push;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;

import com.yidiandao.business.R;
import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.data.bean.Message;
import com.yidiandao.business.data.model.MessageModel;
import com.yidiandao.business.receiver.NotificationClickReceiver;
import com.yidiandao.business.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.UUID;

/**
 * 推送处理
 */
public abstract class AbsPushProcess implements IPushHandler, IPushProcess {

    protected Context mContext;

    /**
     * App是否在前台运行
     */
    private boolean mIsForeground;

    protected Message mMessage;

    // pushEntity   接收到的推送数据
    // isForeground App是否在前台运行
    public AbsPushProcess(Context context, Message message, boolean isForeground) {
        mContext = context;
        mMessage = message;
        mIsForeground = isForeground;
    }


    @Override
    public void processPush() {
        if (mIsForeground) {
            // App在前台运行：
            // 判断是否显示弹窗信息
            showDialog();
        } else {
            // App在后台运行：
            // 所有推送都需要显示
            showNotification();
        }
    }

    @Override
    public void showDialog() {
        EventBus.getDefault().post(mMessage);
    }

    @Override
    public void showNotification() {
        Intent intent = new Intent(mContext, NotificationClickReceiver.class);
        intent.putExtra(Intents.EXTRA_PUSH_TYPE, mMessage.getType());
        intent.putExtra(Intents.EXTRA_MESSAGE_ID, mMessage.getMsgId());

        // 往发送 NotificationClickReceiver 的Intent中注入格外的数据
        addExtraDataToNotificationClickReceiverIntent(intent);

        genNotificationAndSendBroadcastReceiver(mContext, intent, mMessage.getTitle(), mMessage.getContent());
    }

    /**
     * 往发送 NotificationClickReceiver 的Intent中注入格外的数据。
     * <p><b>也就是点击通知栏时，跳转到指定页面需要的额外数据</b>
     * <p><b>注意：不包括要跳转页面的信息，因此此处是发送一个广播的Intent</b>
     */
    protected abstract void addExtraDataToNotificationClickReceiverIntent(Intent intent);


    /**
     * 获取发送广播的PaddingIntent
     *
     * @param intent 打开页面的Intent
     */
    private PendingIntent getPaddingIntent(Context context, Intent intent) {
        // Google 挖了一个坑，WTF，Intent中的Extra会更替换。使用RequestCode修复此bug
        return PendingIntent.getBroadcast(context, UUID.randomUUID().hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }


    /**
     * 生成Notification并显示出来.并发送广播,以监听Notification的点击事件
     */
    private void genNotificationAndSendBroadcastReceiver(Context context, Intent intent, String title, String message) {
        // 通过系统服务来创建NotificationManager
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        //设置点击通知栏时弹出哪一个Activity
        PendingIntent pendingIntent = getPaddingIntent(context, intent);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        // 设置状态栏图标.Google最新规范要求状态栏图标只带 alpha 通道
        builder.setSmallIcon(R.mipmap.logo);
        // 设置通知栏图标
        builder.setLargeIcon(BitmapFactory.decodeResource(UIUtils.getResources(), R.mipmap.logo));
        // 手机状态栏提示
        builder.setTicker(message);
        // 设置时间
        builder.setWhen(System.currentTimeMillis());
        // 设置标题栏
        builder.setContentTitle(title);
        // 设置通知栏内容
        builder.setContentText(message);
        // 设置点击通知栏时弹出哪一个Activity
        builder.setContentIntent(pendingIntent);

        // 设置 提示声音、指示灯、震动
        builder.setDefaults(Notification.DEFAULT_ALL);
        Notification notification = builder.build();

        // 设置点击通知后自动消失
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        // id不能重复
        manager.notify(UUID.randomUUID().hashCode(), notification);
    }


    /**
     * 告知后端消息已读
     */
    protected void tellServerMessageHasRead(String messageId) {
        new MessageModel().setMessageIsRead(getClass().getSimpleName(), messageId, null);
    }
}
